<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/8/27
 * Time: 15:19
 */

namespace Biz\module\Classes;

use Biz\module\Classes\OrderPackage as clsOrderPackage;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\service\Sku;
use Biz\service\trade\Logistics as sLogistics;
use Biz\model\trade\Order as mOrder;
use Biz\model\trade\OrderPackage as mOrderPackage;
use Biz\model\trade\UserAddress as mUserAddress;
use Doraemon\model\Category;
use Doraemon\tools\HhzClient;
use Biz\module\Classes\Order as clsOrder;
use Biz\model\trade\OrderGoods as mOrderGoods;
use Biz\model\GoodsSku as mGoodsSku;
use Biz\model\GoodsExtendInfo as mGoodsExtendInfo;
use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Biz\model\trade\OrderMatching as mOrderMatching;


class OrderInfo implements ActivityInfo
{


    //APP端 根据订单号查询最新的一条物流信息
    public static function getOrderLastOneLogistics($orderNo, &$orderInfo = [])
    {
        $info = sLogistics::getLastLogisticsInfo($orderNo);

        return $info;
    }

    //商家端  根据订单号查询物流信息
    public static function getOrderDeliveryTracking($orderNo, &$orderInfo = [])
    {
        $list = clsOrderPackage::getOrderPackageList($orderNo, false, true);


        return $list;
    }

    public static function getFirstSkuInfo($orderNo, $packageId = 0)
    {
        return mOrderPackage::getFirstSkuInfo($orderNo, $packageId);
    }

    public static function detectOrderType($from = '')
    {
        $orderType = mOrder::ORDER_TYPE_NORMAL;
        if (HhzClient::getClientType() == HhzClient::APPTYPE_TUAN_MINIPROGRAM) {
            $orderType = mOrder::ORDER_TYPE_GROUP_BUY;
        }

        return $orderType;
    }

    public static function detectFromSource()
    {
        $appType = HhzClient::getClientType();

        $fromSource = clsOrder::getOrderFromSource($appType);

        return $fromSource;
    }

    public static function paySuccInfo($uid, $orderPNo, $addressId = 0)
    {
        $res = [
            "furnishing_goods_list" => [],
            "address_info" => '',
            "address_tipinfo" => null,
        ];
        //定义3级家具分类的子分类
        $categories = array_keys(Category::CATEGORY_FURNITURE_DEEP_3);

        $orderInfoList = mOrder::getOrderInfoList(['order_parent_no' => $orderPNo]);

        if (empty($orderInfoList)) {
            throw new \Exception('订单不存在');
        }

        $firstOrderInfo = $orderInfoList[0];

        if ($firstOrderInfo['uid'] != $uid) {
            throw new \Exception('订单不存在');
        }

        $orderNos = array_column($orderInfoList, 'order_no');

        $res["address_info"] = $firstOrderInfo['consignee_address'];


        //查询订单下面的所有商品的列表
        $skuList = mOrderGoods::getOrderGoodsList($orderNos);

        //拿到goodsidlist
        $goodsIds = array_column($skuList, 'goods_id', 'sku_id');
        $uniqGoodsIds = array_unique(array_values($goodsIds));
        $skuOrderNoSuffixMaps = array_map(function ($v) {
            preg_match('/(\d+)$/', $v, $matches);

            return $matches[1];
        }, array_column($skuList, 'order_no', 'sku_id'));

        //查询所有SPU维度的信息，来筛选家居品类的商品
        $goodsInfoList = mGoodsBasicInfo::getGoodsByWhere('select', '*', ['goods_id' => $uniqGoodsIds, 'third_category_id' => $categories]);

        //如果没有家具品类的商品，则直接返回
        if (empty($goodsInfoList)) {
            return $res;
        }

        //拿到需要的goods_ids列表
        $needGoodsIds = array_column($goodsInfoList, 'goods_id');
        //拿到经过筛选品类后剩下需要的skuId
        $needSkuIds = array_keys(array_filter($goodsIds, function ($v) use ($needGoodsIds) {
            if (in_array($v, $needGoodsIds)) {
                return true;
            }
            return false;
        }));

        //查询sku级别商家填写的预计发货时间
        $goodsSkuList = mGoodsSku::getInfoList($needSkuIds, false, false);

        //查询商品填写的发货时间
        $goodsExtInfos = mGoodsExtendInfo::getInfoList($needGoodsIds, false);

        $skuInfoList = Sku::Sku4Order($needSkuIds);

        //格式化输出furnishing_goods_list字段
        $res['furnishing_goods_list'] = array_values(array_map(function ($v) use (&$skuList, $goodsSkuList, $goodsExtInfos, $skuOrderNoSuffixMaps) {
            //初始化返回数据，并组装基本信息
            $data = $v;
            $data['title'] = $v['goods_info']['title'];
            $data['suffix_id'] = $skuOrderNoSuffixMaps[$v['sku_id']];

            //商家填写的预计发货时间
            $forecastShipTime = strtotime($goodsSkuList[$v['sku_id']]['forecast_ship_time']);

            if ($forecastShipTime > 0) {
                $data['ship_time']['start_time'] = date('Y-m-d', $forecastShipTime);
                $data['ship_time']['stop_time'] = date('Y-m-d', $forecastShipTime + 5184000);
            } else {
                $goodsExtInfo = $goodsExtInfos[$data['goods_id']];

                $beginTime = 0;
                $nowTime = time();

                if ($goodsExtInfo['shipping_time_type'] == mGoodsExtendInfo::SHIPPING_TIME_TYPE_SPOT) {
                    $beginTime = $goodsExtInfo['shipping_time'] * 3600;
                } elseif ($goodsExtInfo['shipping_time_type'] == mGoodsExtendInfo::SHIPPING_TIME_TYPE_PRE_SALE) {
                    $beginTime = $goodsExtInfo['shipping_time'] * 86400;
                }

                $data['ship_time']['start_time'] = date('Y-m-d', $nowTime + $beginTime);
                $data['ship_time']['stop_time'] = date('Y-m-d', $nowTime + $beginTime + 5184000);
            }

            return $data;
        }, $skuInfoList));


        //根据用户选择的地址，查询地址信息
        if (empty($addressId)) {
            return $res;
        }

        $addressInfo = mUserAddress::getById($addressId);

        if (empty($addressInfo) || (!empty($addressInfo) && $addressInfo['uid'] != $uid)) {
            throw new \Exception('参数传递错误');
        }

        $res['address_tipinfo'] = [
            'can_enter_community' => $addressInfo['can_enter_community'],
            'have_elevator' => $addressInfo['have_elevator'],
            'which_floor' => $addressInfo['which_floor'],
        ];

        return $res;
    }

    public static function matchingSave($uid, $orderPNo, $addressId, $addressTipInfo, $receiptTimeList)
    {
        $orderInfoList = mOrder::getOrderInfoList(['order_parent_no' => $orderPNo]);

        if (empty($orderInfoList)) {
            throw new \Exception('订单不存在');
        }
        $firstOrderInfo = $orderInfoList[0];

        if ($firstOrderInfo['uid'] != $uid) {
            throw new \Exception('订单不存在');
        }

        $orderPrefix = trim($orderPNo, "-P");

        //判断收货设置是否填写，如果填写，那么则对应的保存到指定的收货地址下面
        if (!empty($addressTipInfo)) {

            if ($addressId > 0) {
                $addressInfo = mUserAddress::getById($addressId);

                if (empty($addressInfo) || (!empty($addressInfo) && $addressInfo['uid'] != $uid)) {
                    throw new \Exception('参数传递错误');
                }

                mUserAddress::saveAddressById($addressId, [
                    'can_enter_community' => $addressTipInfo['can_enter_community'],
                    'have_elevator' => $addressTipInfo['have_elevator'],
                    'which_floor' => $addressTipInfo['which_floor'],
                ], false);
            }

            foreach ($orderInfoList as $orderInfo) {

                //查询预约信息是否填写
                $orderMatching = mOrderMatching::getInfo($orderInfo['order_no']);

                $upData = [
                    'is_inter_community' => $addressTipInfo['can_enter_community'],
                    'is_has_elevator' => $addressTipInfo['have_elevator'],
                    'which_floor' => $addressTipInfo['which_floor']
                ];

                //如果存在就更新
                if (!empty($orderMatching[0])) {
                    mOrderMatching::update($upData, ['order_no' => $orderInfo['order_no']]);
                } else {
                    mOrderMatching::insert(array_merge(['order_no' => $orderInfo['order_no']], $upData));
                }
            }
        }

        if (!empty($receiptTimeList)) {
            foreach ($receiptTimeList as $receiptTimeInfo) {
                mOrderGoods::update([
                    'reserve_receipt_time' => $receiptTimeInfo['receipt_time'],
                ], ['order_no' => $orderPrefix . "-" . $receiptTimeInfo['suffix_id'], 'sku_id' => $receiptTimeInfo['sku_id']]);
            }
        }

    }

    public static function checkHeavyGoodsByOrderNo($orderNo)
    {
        $count = 0;

        $categories = array_keys(Category::CATEGORY_FURNITURE_DEEP_3);

        //查询订单下面的所有商品的列表
        $skuList = mOrderGoods::getOrderGoodsList($orderNo);

        //拿到goodsidlist
        if ($skuList && !empty($categories)) {
            $goodsIds = array_column($skuList, 'goods_id', 'sku_id');
            $uniqGoodsIds = array_unique(array_values($goodsIds));

            //查询所有SPU维度的信息，来筛选家居品类的商品
            $count = mGoodsBasicInfo::getGoodsCount(['goods_id' => $uniqGoodsIds, 'third_category_id' => $categories]);
        }
        return $count;
    }
}